﻿using EBA.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;

namespace EBA.Framework
{


    /// <summary>
    /// 插件安装器
    /// </summary>
    public class BundleInstaller<TBundle> : IDisposable where TBundle:IBundle
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configPath"></param>
        public BundleInstaller(string configPath = null)
        {
            this.Configuration = new FrameworkConfiguration(configPath);
        }

        /// <summary>
        /// 框架配置信息
        /// </summary>
        protected FrameworkConfiguration Configuration { get; set; }

        /// <summary>
        /// 搜索指定文件夹获取插件信息。
        /// </summary>
        /// <param name="folder">插件所在文件夹</param>
        public virtual void Install(string folder)
        {
            Contract.Requires<ArgumentNullException>(folder != null, "folder");
            Contract.Requires<DirectoryNotFoundException>(Directory.Exists(folder), folder);

            var manifests = this.BundleAnalyzer.GetBundleManifests<TBundle>(folder).ToArray();

            if (manifests.Length == 0)
            {
                throw new BundleImplNotFoundException();
            }
            else if (manifests.Length > 1)
            {
                throw new MultiBundlesNotSupportedException();
            }

            var manifest = manifests[0];

            this.Install(manifest);
         
        }

        /// <summary>
        /// 根据插件清单安装插件到指定的运行的配置文件中。
        /// </summary>
        /// <param name="manifest"></param>
        public virtual void Install(BundleManifest manifest)
        {
            Contract.Requires<ArgumentNullException>(manifest != null, "manifest");

            var bundleDir = Path.Combine(AppRuntime.ApplicationPath, this.Configuration.Framework.Plugins, manifest.Bundle.Id);

            var bundleConfig = this.Configuration.Framework.Bundles.GetElement(manifest.Bundle.Id);
            if (bundleConfig == null)
            {
                bundleConfig = new BundleConfigurationElement();
            }


            bundleConfig.Name = manifest.Bundle.Name;
            bundleConfig.Description = manifest.Bundle.Description;
            bundleConfig.Version = manifest.Bundle.Version.ToString();
            bundleConfig.Context = BundleContext.DefaultName;//默认使用进程内

            if (Directory.Exists(bundleDir) == false)
            {
                Directory.CreateDirectory(bundleDir);
            }

            foreach (var file in manifest.Files)
            {
                bundleConfig.Files.Add(file);

                var fileInfo = new FileInfo(file);

                File.Copy(file, Path.Combine(bundleDir, fileInfo.Name), true);
            }

            if (string.IsNullOrWhiteSpace(bundleConfig.Id))
            {
                bundleConfig.Id = manifest.Bundle.Id;
                this.Configuration.Framework.Bundles.Add(bundleConfig);
            }

            this.Configuration.SaveConfig();
        }

        AppDomain _AnalyzerAppDomain;
        AppDomain AnalyzerAppDomain
        {
            get
            {
                if (this._AnalyzerAppDomain == null)
                {
                    Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
                    AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
                    this._AnalyzerAppDomain = AppDomain.CreateDomain(string.Format("BundleAnalyzer-{0}", Guid.NewGuid().ToString()),
                        evidence, setup);
                }

                return this._AnalyzerAppDomain;
            }
        }

        BundleAnalyzer _BundleAnalyzer;
        BundleAnalyzer BundleAnalyzer
        {
            get
            {
                if (this._BundleAnalyzer == null)
                {
                    Type analyzerType = typeof(BundleAnalyzer);

                    this._BundleAnalyzer = (BundleAnalyzer)this.AnalyzerAppDomain.CreateInstanceFrom(analyzerType.Assembly.Location, analyzerType.FullName).Unwrap();
                }

                return this._BundleAnalyzer;
            }
        }

        #region Dispose
        private bool _Disposed = false;
        /// <summary>
        /// 析构函数，释放资源。
        /// </summary>
        ~BundleInstaller()
        {
            Dispose(false);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }


        /// <summary>
        /// 手动释放资源
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_Disposed)
            {
                if (disposing)
                {
                    if (this._AnalyzerAppDomain != null)
                    {
                        AppDomain.Unload(this._AnalyzerAppDomain);
                        this._AnalyzerAppDomain = null;
                    }

                    GC.SuppressFinalize(this);
                }
                _Disposed = true;
            }
        }
        #endregion

    }
}
